'''
千万综合交通意外险
'''

import sys

sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
from urllib.parse import urlencode
import requests, time
from common.helper import Helper


class Spider(object):
    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "千万综合交通意外险"

    # 生成产品信息
    def genProductInfo(self):

        # 保障天数
        days = ["365", "180", "90", "30", "7"]
        # 被保险人数 0-17
        interval_zero = [i for i in range(11)]

        interval_eighteen = interval_zero[::-1]

        interval_eighteen.remove(0)

        for v in product(days, interval_zero, interval_eighteen):

            if (v[1] + v[2]) > 10:
                continue

            # 写入数据库
            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(v[0], str(v[1]), str(v[2])))

            self.mysql._conn.commit()

            print("%s写入数据库成功" % self.name)

        # 被保险人数 18 - 81

        '''
        
        1 -- 0  1 -- 1
        
        2 -- 0  2 -- 1
        
        3 -- 0  3 -- 1
        
        ...
        
        
        '''

    # 执行爬虫脚本
    def requestJson(self, dt=None):

        if dt["day"] == "365":

            data = {

                "cityCode": "310100",
                "cityName": "上海市",
                "provinceCode": "310000",
                "provinceName": "上海市",
                "planCode": "P03",
                "departmentCode": "5",
                "pageInfo": "bralirantTravel",
                "analysisPageInfo": "luck_index",
                "isAgent": "null",
                "ms": "",
                "insuredNum": "1",
                "isSave": "true",
                "userName": "",
                "openCmsUrl": "https: // www.axa.cn",
                "planDefineId": "P03007",
                "firstPlanId": "P03007",
                "isAjax": "1",
                "allYear": "0",
                "isPc": "Y",
                "isHaveEnsureDays": "Y",
                "select_city": "上海市",
                "insureDays": dt["day"],
                "contractBeginDate": "2019-12-18",
                "contractEndDate": "2020-12-16",
                "juveniles": dt["interval_zero"],
                "adult": dt["interval_eighteen"],
                "requestTypeIsAjax": "1",

            }

        elif dt["day"] == "180":

            data = {

                "cityCode": "310100",
                "cityName": "上海市",
                "provinceCode": "310000",
                "provinceName": "上海市",
                "planCode": "P03",
                "departmentCode": "5",
                "pageInfo": "bralirantTravel",
                "analysisPageInfo": "luck_index",
                "isAgent": "null",
                "ms": "",
                "insuredNum": "1",
                "isSave": "true",
                "userName": "",
                "openCmsUrl": "https: // www.axa.cn",
                "planDefineId": "P03007",
                "firstPlanId": "P03007",
                "isAjax": "1",
                "allYear": "0",
                "isPc": "Y",
                "isHaveEnsureDays": "Y",
                "select_city": "上海市",
                "insureDays": dt["day"],
                "contractBeginDate": "2019-12-18",
                "contractEndDate": "2020-06-14",
                "juveniles": dt["interval_zero"],
                "adult": dt["interval_eighteen"],
                "requestTypeIsAjax": "1",

            }

        elif dt["day"] == "90":

            data = {

                "cityCode": "310100",
                "cityName": "上海市",
                "provinceCode": "310000",
                "provinceName": "上海市",
                "planCode": "P03",
                "departmentCode": "5",
                "pageInfo": "bralirantTravel",
                "analysisPageInfo": "luck_index",
                "isAgent": "null",
                "ms": "",
                "insuredNum": "1",
                "isSave": "true",
                "userName": "",
                "openCmsUrl": "https: // www.axa.cn",
                "planDefineId": "P03007",
                "firstPlanId": "P03007",
                "isAjax": "1",
                "allYear": "0",
                "isPc": "Y",
                "isHaveEnsureDays": "Y",
                "select_city": "上海市",
                "insureDays": dt["day"],
                "contractBeginDate": "2019-12-18",
                "contractEndDate": "2020-03-16",
                "juveniles": dt["interval_zero"],
                "adult": dt["interval_eighteen"],
                "requestTypeIsAjax": "1",

            }

        elif dt["day"] == "30":

            data = {

                "cityCode": "310100",
                "cityName": "上海市",
                "provinceCode": "310000",
                "provinceName": "上海市",
                "planCode": "P03",
                "departmentCode": "5",
                "pageInfo": "bralirantTravel",
                "analysisPageInfo": "luck_index",
                "isAgent": "null",
                "ms": "",
                "insuredNum": "1",
                "isSave": "true",
                "userName": "",
                "openCmsUrl": "https: // www.axa.cn",
                "planDefineId": "P03007",
                "firstPlanId": "P03007",
                "isAjax": "1",
                "allYear": "0",
                "isPc": "Y",
                "isHaveEnsureDays": "Y",
                "select_city": "上海市",
                "insureDays": dt["day"],
                "contractBeginDate": "2019-12-18",
                "contractEndDate": "2020-01-16",
                "juveniles": dt["interval_zero"],
                "adult": dt["interval_eighteen"],
                "requestTypeIsAjax": "1",

            }
        elif dt["day"] == "7":

            data = {

                "cityCode": "310100",
                "cityName": "上海市",
                "provinceCode": "310000",
                "provinceName": "上海市",
                "planCode": "P03",
                "departmentCode": "5",
                "pageInfo": "bralirantTravel",
                "analysisPageInfo": "luck_index",
                "isAgent": "null",
                "ms": "",
                "insuredNum": "1",
                "isSave": "true",
                "userName": "",
                "openCmsUrl": "https: // www.axa.cn",
                "planDefineId": "P03007",
                "firstPlanId": "P03007",
                "isAjax": "1",
                "allYear": "0",
                "isPc": "Y",
                "isHaveEnsureDays": "Y",
                "select_city": "上海市",
                "insureDays": dt["day"],
                "contractBeginDate": "2019-12-18",
                "contractEndDate": "2019-12-24",
                "juveniles": dt["interval_zero"],
                "adult": dt["interval_eighteen"],
                "requestTypeIsAjax": "1",

            }

        # data = {'cityCode': '310100', 'cityName': '上海市', 'provinceCode': '310000', 'provinceName': '上海市',
        #         'planCode': 'P03', 'departmentCode': '5', 'pageInfo': 'bralirantTravel',
        #         'analysisPageInfo': 'luck_index', 'isAgent': 'null', 'ms': '', 'insuredNum': '1', 'isSave': 'true',
        #         'userName': '', 'openCmsUrl': 'https://www.axa.cn', 'planDefineId': 'P03007', 'firstPlanId': 'P03007',
        #         'isAjax': '1', 'allYear': '0', 'isPc': 'Y', 'isHaveEnsureDays': 'Y', 'select_city': '上海市',
        #         'insureDays': '7', 'contractBeginDate': '2019-12-18', 'contractEndDate': '2020-12-24', 'juveniles': '1',
        #         'adult': '6', 'requestTypeIsAjax': '1'}

        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=urlencode(data))

        if r.status_code == 200 and "totalActualPremium" in r.json()["data"]:

            price = r.json()["data"][
                "totalActualPremium"
            ]

            data = {

                "name":self.name,
                "id":dt["id"],
                "price":Helper.decimalParse( price )
            }
            self.mysql.updatePrice( data )

        else:

            # 任务执行失败
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            self.mysql.updateTask(data)
            print("产品价格更新失败:", dt["id"])

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)


if __name__ == '__main__':
    s = Spider()
    # s.genProductInfo()
    s.main()
